/**
 * 认证状态管理
 *
 * 使用zustand管理用户认证状态
 * zustand是一个轻量级的状态管理库，比Redux更简单
 */
import { create } from 'zustand';
import { User, LoginRequest } from '../types';
import { authService } from '../services/authService';

interface AuthState {
  // 状态
  user: User | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  error: string | null;

  // 动作
  login: (credentials: LoginRequest) => Promise<{ success: boolean; error?: string }>;
  logout: () => void;
  getCurrentUser: () => Promise<void>;
  clearError: () => void;
  initializeAuth: () => void;
  isAdmin: () => boolean;
}

/**
 * 认证状态store
 *
 * 这个store演示了如何使用zustand管理复杂的异步状态
 */
export const useAuthStore = create<AuthState>((set, get) => ({
  // 初始状态
  user: null,
  isAuthenticated: false,
  isLoading: false,
  error: null,

  /**
   * 用户登录
   */
  login: async (credentials: LoginRequest) => {
    set({ isLoading: true, error: null });

    try {
      // 调用登录API
      await authService.login(credentials);

      // 获取用户信息
      const user = await authService.getCurrentUser();

      set({
        user,
        isAuthenticated: true,
        isLoading: false
      });

      return { success: true };
    } catch (error: any) {
      const errorMessage = error.response?.data?.detail || '登录失败';
      set({
        error: errorMessage,
        isLoading: false
      });
      return { success: false, error: errorMessage };
    }
  },

  /**
   * 用户登出
   */
  logout: () => {
    authService.logout();
    set({
      user: null,
      isAuthenticated: false,
      error: null
    });
  },

  /**
   * 获取当前用户信息
   */
  getCurrentUser: async () => {
    set({ isLoading: true, error: null });

    try {
      const user = await authService.getCurrentUser();
      set({
        user,
        isAuthenticated: true,
        isLoading: false
      });
    } catch (error: any) {
      // 如果获取用户信息失败，清除认证状态
      authService.logout();
      set({
        user: null,
        isAuthenticated: false,
        isLoading: false,
        error: error.response?.data?.detail || '获取用户信息失败'
      });
    }
  },

  /**
   * 清除错误信息
   */
  clearError: () => {
    set({ error: null });
  },

  /**
   * 初始化认证状态
   * 应用启动时调用，检查本地存储的认证信息
   */
  initializeAuth: () => {
    const isAuthenticated = authService.isAuthenticated();
    const storedUser = authService.getStoredUser();

    if (isAuthenticated && storedUser) {
      set({
        user: storedUser,
        isAuthenticated: true
      });
    } else {
      // 清除无效的认证信息
      authService.logout();
      set({
        user: null,
        isAuthenticated: false
      });
    }
  },

  /**
   * 检查是否为管理员
   */
  isAdmin: () => {
    const { user } = get();
    return user?.role === 'admin';
  },
}));